package com.ymk.ctrl;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.cmd.SchedulerCmd;
import com.ymk.base.exception.MallException;
import com.ymk.base.service.WxService;
import com.ymk.base.service.impl.OssService;
import com.ymk.base.utlis.ExcelUtils;
import com.ymk.base.utlis.LogUtils;
import com.ymk.bo.work.WorkEntryBO;
import com.ymk.bo.work.WorkEntryDataV2;
import com.ymk.core.code.resp.RespCode;
import com.ymk.core.constants.SysConstants;
import com.ymk.service.impl.DyService;
import com.ymk.service.impl.WorkEntryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

@Controller
public class HttpHandlerCtrl {
    private final static Logger logger = LoggerFactory.getLogger(HttpHandlerCtrl.class);

    @RequestMapping("/downloadExcel")
    public void getExcel(HttpServletResponse response, @RequestParam String startDate, @RequestParam String endDate, @RequestParam String uniqueId) throws IOException {

        WorkEntryBO workEntryBO = new WorkEntryBO();
        workEntryBO.setStartDate(startDate);
        workEntryBO.setEndDate(endDate);
        workEntryBO.setUniqueId(uniqueId);
        // 查询数据
        List<WorkEntryBO> list = workEntryService.downloadExcel(workEntryBO);

        List<WorkEntryDataV2> data = new ArrayList<>();
        for (WorkEntryBO workEntry : list){
            //创建封装对象
            WorkEntryDataV2 workEntryData = new WorkEntryDataV2();
            if (Objects.nonNull(workEntry.getType()) && workEntry.getType() == 2){
                workEntryData.setSource("直播间");
            }
            else if (Objects.nonNull(workEntry.getType()) && workEntry.getType() == 1){
                workEntryData.setSource("短视频");
            }else {
                workEntryData.setSource("正常进入小程序");
            }
            // copy 数据
            BeanUtils.copyProperties(workEntry,workEntryData);
            // 添加到导出集合
            data.add(workEntryData);
        }
        //导出excel
        ExcelUtils.download(response, WorkEntryDataV2.class,data);

    }
        @RequestMapping(path = "/oss/api", method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    String ssoApi(@RequestParam("file") MultipartFile file) {
        try {
            return this.ossService.ossUpload(file);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    @ResponseBody
    String uploadFile(@RequestBody String body, HttpServletRequest request) {
        try {
            JSONObject json = JSON.parseObject(body);
            String fileData = json.getString("data");

            // 获取解码器
            Base64.Decoder decoder = Base64.getDecoder();
            // 对编码后的字符串进行解码
            byte[] bytes = decoder.decode(fileData);
            // 文件存储路径
            String path = "idcard/"+ IdUtil.simpleUUID()+".jpg";
            // 上传文件
            String fileId = wxService.uploadFileData(bytes,path);

            CmdSign cmdSign = new CmdSign();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("filePath",fileId);
            cmdSign.setSource(jsonObject.toString());
           return cmdSign.toString();
        } catch (Exception e) {
            //logger.error(body);
            logger.error(e.getMessage(), e);
        }
        return "";
    }


    @RequestMapping(path = "/server/api", method = RequestMethod.POST)
    @ResponseBody
    String serverApi(@RequestBody String body, HttpServletRequest request) {
        try {
            CmdSign cmdSign = new Gson().fromJson(body, CmdSign.class);
            cmdSign.setScope(SysConstants.CMD_SERVER_SCOPE);
            return this.execute(cmdSign, request).toString();
        } catch (Exception e) {
            logger.error(body);
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    @RequestMapping(path = "/sop/api", method = RequestMethod.POST)
    @ResponseBody
    String supApi(@RequestBody String body, HttpServletRequest request) {
        try {
            CmdSign cmdSign = new Gson().fromJson(body, CmdSign.class);
            cmdSign.setScope(SysConstants.CMD_SOP_SCOPE);
            return this.execute(cmdSign, request).toString();
        } catch (Exception e) {
            logger.error(body);
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    @RequestMapping(path = "/mop/api", method = RequestMethod.POST)
    @ResponseBody
    String mopApi(@RequestBody String body, HttpServletRequest request) {
        try {
            CmdSign cmdSign = new Gson().fromJson(body, CmdSign.class);
            cmdSign.setScope(SysConstants.CMD_MOP_SCOPE);
            return this.execute(cmdSign, request).toString();
        } catch (Exception e) {
            logger.error(body);
            logger.error(e.getMessage(), e);
        }
        return "";
    }


    @RequestMapping(path = "/store/api", method = RequestMethod.POST)
    @ResponseBody
    String storeApi(@RequestBody String body, HttpServletRequest request) {
        try {
            CmdSign cmdSign = new Gson().fromJson(body, CmdSign.class);
            cmdSign.setScope(SysConstants.CMD_STORE_SCOPE);
            return this.execute(cmdSign, request).toString();
        } catch (Exception e) {
            logger.error(body);
            logger.error(e.getMessage(), e);
        }
        return "";
    }
    @PostMapping("author")
    @ResponseBody
    public String getDouYinAauthor(@RequestBody String body)  {
        JSONObject json = JSONObject.parseObject(body);
        logger.info("======收到推送的author消息===== "+json.toJSONString());
        try {
            this.dyService.save(json,SysConstants.AUTHOR);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "success";
    }
    @PostMapping("message/$APPID$")
    @ResponseBody
    public String getDouYinMessage(@RequestBody String body){
        JSONObject json = JSONObject.parseObject(body);
        logger.info("======收到推送的message消息===== "+json.toJSONString());
        try {
            this.dyService.save(json,SysConstants.MESSAGE);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "success";
    }

    private CmdSign execute(CmdSign cmdSign, HttpServletRequest request) {
        CmdSign respSign = null;
        try {
            respSign = this.scheduler.schedule(request, cmdSign);
        } catch (MallException e) {
            cmdSign.endExe();
            respSign = new CmdSign(cmdSign);
            respSign.setRespCode(e.getRespCode());
            respSign.setMsg(e.getMsg());
            LogUtils.auditLog(logger, cmdSign, "", respSign.getMsg());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (cmdSign != null) {
                logger.error(new Gson().toJson(cmdSign));
                cmdSign.endExe();
                respSign = new CmdSign(cmdSign);
                respSign.setRespCode(RespCode.CODE_ERROR);
                respSign.setMsg("异常操作，请联系服务商");
            }
        }
        // 效率日志
        // LogUtils.statLog(logger, cmdSign, LogUtils.LOG_GROUP_STAT_CMD);
        if (respSign == null) {
            cmdSign.setMsg("execute return null");
            logger.error(new Gson().toJson(cmdSign));
        }
        return respSign;
    }



    @Autowired
    private DyService dyService;
    @Autowired
    private SchedulerCmd scheduler;
    @Autowired
    private OssService ossService;

    @Autowired
    private WorkEntryService workEntryService;
    @Autowired
    private WxService wxService;
}
